<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        .game-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            width: 420px;
        }
        h1 {
            margin-bottom: 20px;
        }
        .board {
            display: grid;
            grid-template-columns: repeat(20, 20px);
            gap: 1px;
            margin-bottom: 20px;
            background-color: #ddd;
        }
        .cell {
            width: 20px;
            height: 20px;
            background-color: #fff;
        }
        .snake {
            background-color: green;
        }
        .food {
            background-color: red;
        }
        .status {
            font-size: 18px;
            margin-bottom: 10px;
        }
        .reset-button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .reset-button:hover {
            background-color: #218838;
        }
        .exit {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .exit:hover {
            background-color: #218838;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>贪吃蛇游戏</h1>
        <div class="board" id="board"></div>
        <div class="status" id="status">分数: 0</div>
        <button class="reset-button" id="reset-button">重新开始</button>
        <button class="exit" id="exit">back</button>
    </div>

    <script>
        const board = document.getElementById('board');
        const status = document.getElementById('status');
        const resetButton = document.getElementById('reset-button');
        document.addEventListener('DOMContentLoaded', function () {
    // 获取"返回首页"按钮
    var exitButton = document.getElementById('exit');

    // 为"返回首页"按钮添加点击事件监听器
    if (exitButton) {
        exitButton.addEventListener('click', function () {
            // 点击按钮后重定向到首页
            window.location.href = 'index.html';
        });
    }
});

        const gridSize = 20;
        let snake = [{ x: 10, y: 10 }];
        let food = { x: 5, y: 5 };
        let lastFoodPosition = { x: -1, y: -1 }; // Track the last position of food to prevent consecutive same positions
        let direction = { x: 0, y: -1 }; // Default direction is up
        let score 
        let gameOver = false;

        function createBoard() {
            board.innerHTML = '';
            for (let i = 0; i < gridSize * gridSize; i++) {
                const cell = document.createElement('div');
                cell.classList.add('cell');
                board.appendChild(cell);
            }
        }

        function draw() {
            const cells = document.querySelectorAll('.cell');
            cells.forEach(cell => cell.classList.remove('snake', 'food')); // Clear all classes first

            snake.forEach(segment => {
                const index = segment.y * gridSize + segment.x;
                cells[index].classList.add('snake');
            });

            const foodIndex = food.y * gridSize + food.x;
            cells[foodIndex].classList.add('food');
        }

        function update() {
            if (gameOver) return;

            const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };

            // Check for wall collision
            if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {
                gameOver = true;
                alert('撞墙了！游戏结束！');
                clearInterval(gameInterval);
                return;
            }

            // Check for self collision
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    gameOver = true;
                    alert('撞到自己了！游戏结束！');
                    clearInterval(gameInterval);
                    return;
                }
            }

            // Check for food collision
            if (head.x === food.x && head.y === food.y) {
                score++;
                status.textContent = `分数: ${score}`;
                placeFood();
            } else {
                snake.pop(); // Remove the tail
            }

            // Add new head to the snake
            snake.unshift(head);

            draw();
        }

        function placeFood() {
            do {
                food.x = Math.floor(Math.random() * gridSize);
                food.y = Math.floor(Math.random() * gridSize);
            } while (snake.some(segment => segment.x === food.x && segment.y === food.y) || 
                     (food.x === lastFoodPosition.x && food.y === lastFoodPosition.y));

            lastFoodPosition = { x: food.x, y: food.y };
        }

        function changeDirection(event) {
            const newDirection = {
                ArrowUp: { x: 0, y: -1 },
                ArrowDown: { x: 0, y: 1 },
                ArrowLeft: { x: -1, y: 0 },
                ArrowRight: { x: 1, y: 0 }
            }[event.key];

            if (newDirection && 
                (direction.x === 0 || newDirection.x === 0) && // Prevent reversing
                (direction.y === 0 || newDirection.y === 0)) {
                direction = newDirection;
            }
        }

        function startGame() {
            createBoard();
            placeFood();
            draw();
            gameInterval = setInterval(update, 100);
            document.addEventListener('keydown', changeDirection);
        }

        function resetGame() {
            clearInterval(gameInterval);
            document.removeEventListener('keydown', changeDirection);
            snake = [{ x: 10, y: 10 }];
            direction = { x: 0, y: -1 }; // Reset to default direction
            score = 0;
            gameOver = false;
            status.textContent = `分数: ${score}`;
            lastFoodPosition = { x: -1, y: -1 }; // Reset last food position
            startGame();
        }

        resetButton.addEventListener('click', resetGame);
        startGame();
    </script>
</body>
</html>